/**
 * Project: springyounger.lottery.web
 * 
 * File Created at 2010-4-15
 * $Id$
 * 
 * Copyright 2009 Zjut Croporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Zjut Edu. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Zjut Edu.
 */
package com.springyouner.lottery.admin;

import java.awt.Color;
import java.awt.Font;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.DateTickUnit;
import org.jfree.chart.axis.DateTickUnitType;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardXYItemLabelGenerator;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.TextAnchor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.springyouner.lottery.tools.LotteryUtil;
import com.springyounger.lottery.dal.dataobject.LotteryPhase;
import com.springyounger.lottery.dal.dataobject.LotteryStatistical;
import com.springyounger.lottery.service.user.PhaseService;

/**
 * 统计
 * 
 * @author springyounger
 */
public class AdminStatisticController extends MultiActionController {

	private PhaseService phaseService;
	private static final Logger logger = LoggerFactory
			.getLogger(AdminStatisticController.class);

	@SuppressWarnings("unchecked")
	public ModelAndView diplayPhase(HttpServletRequest request,
			HttpServletResponse response, String filename) throws Exception {

		// 显示已经开始或者结束的活动
		Map model = new HashMap();
		// 当前日期
		Date today = LotteryUtil.getToday();
		List<LotteryPhase> allPhaseList = phaseService.getPhases();
		List<LotteryPhase> phaseList = new ArrayList<LotteryPhase>();
		for (LotteryPhase phase : allPhaseList) {
			if (LotteryUtil.getQuot(today, phase.getGmtStart()) <= 0) {
				phaseList.add(phase);
			}
		}

		model.put("filename", filename);
		model.put("phaseList", phaseList);
		return new ModelAndView("admin/stat", model);
	}

	public ModelAndView diplayImage(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("phaseId");
		String filename = null;

		if (LotteryUtil.isEmpty(id) || !LotteryUtil.isNumeric(id)) {
			return diplayPhase(request, response, "");
		}

		int phaseId = Integer.parseInt(id);

		LotteryPhase phase = phaseService.getPhaseById(phaseId);
		List<LotteryStatistical> statList = phaseService.getStat(phase
				.getPhaseId());
		if (null == statList || statList.size() == 0) {
			filename = "";
			// 列表为空
			return diplayPhase(request, response, filename);
		}
		// 统计图
		XYDataset paramXYDataset = createYearDataset(statList);

		response.setContentType("image/jpeg");

		JFreeChart localJFreeChart = ChartFactory.createTimeSeriesChart(phase
				.getPhaseName(), "获奖日期", "人数(人)", paramXYDataset, true, true,
				false);

		// xy轴
		XYPlot localXYPlot = (XYPlot) localJFreeChart.getPlot();
		// 设置图片上的点
		XYItemRenderer xyitem = localXYPlot.getRenderer();
		xyitem.setBaseItemLabelsVisible(true);
		xyitem.setBasePositiveItemLabelPosition(new ItemLabelPosition(
				ItemLabelAnchor.INSIDE1, TextAnchor.BASELINE_CENTER));
		xyitem.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());
		xyitem.setBaseItemLabelFont(new Font("Dialog", 2, 9));
		localXYPlot.setRenderer(xyitem);

		DateAxis localDateAxis = (DateAxis) localXYPlot.getDomainAxis();
		// 显示的间隔
		localDateAxis.setTickUnit(new DateTickUnit(DateTickUnitType.DAY, 1,
				new SimpleDateFormat("yy-M-d")));

		localDateAxis.setPositiveArrowVisible(true);// 增加横轴的箭头

		// localXYPlot.get
		// localDateAxis.setVerticalTickLabels(false);
		XYLineAndShapeRenderer localXYLineAndShapeRenderer = (XYLineAndShapeRenderer) localXYPlot
				.getRenderer();

		localXYLineAndShapeRenderer.setBaseShapesVisible(true);
		// 设置颜色
		localXYLineAndShapeRenderer.setSeriesFillPaint(0, Color.red);
		localXYLineAndShapeRenderer.setSeriesFillPaint(1, Color.white);

		localXYLineAndShapeRenderer.setUseFillPaint(true);

		// 解决中文乱码问题,共要处理这三部分
		// １、对标题
		Font font1 = new Font("SimSun", 10, 20); // 设定字体、类型、字号
		localJFreeChart.getTitle().setFont(font1); // 标题

		// ２、对图里面的汉字设定,也就是plot的设定
		Font font2 = new Font("SimSun", 10, 16); // 设定字体、类型、字号
		localXYPlot.getDomainAxis().setLabelFont(font2);// 相当于横轴或理解为X轴
		localXYPlot.getRangeAxis().setLabelFont(font2);// 相当于竖轴理解为Y轴
		localXYPlot.getRangeAxis().setPositiveArrowVisible(true);
		// 3、下面的方块区域是 LegendTitle 对象
		Font font3 = new Font("SimSun", 10, 12); // 设定字体、类型、字号
		localJFreeChart.getLegend().setItemFont(font3);// 最下方

		// ChartUtilities
		// .writeChartAsJPEG(response.getOutputStream(), localJFreeChart, 600,
		// 400, null);
		filename = ServletUtilities.saveChartAsJPEG(localJFreeChart, 750, 340,
				null);

		return diplayPhase(request, response, filename);
	}

	@SuppressWarnings("unchecked")
	public ModelAndView displayInsertStat(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map model = new HashMap();
		// 当前日期
		Date today = LotteryUtil.getToday();
		List<LotteryPhase> allPhaseList = phaseService.getPhases();
		List<LotteryPhase> phaseList = new ArrayList<LotteryPhase>();
		// 正在进行的活动
		for (LotteryPhase phase : allPhaseList) {
			if (LotteryUtil.getQuot(today, phase.getGmtStart()) <= 0
					&& LotteryUtil.getQuot(today, phase.getGmtEnd()) >= 0) {
				phaseList.add(phase);
			}
		}

		model.put("phaseList", phaseList);
		return new ModelAndView("admin/insertStat", model);
	}

	@SuppressWarnings("unchecked")
	public ModelAndView insertStat(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String message;
		Map model = new HashMap();
		// 当前日期
		Date today = LotteryUtil.getToday();
		List<LotteryPhase> allPhaseList = phaseService.getPhases();
		List<LotteryPhase> phaseList = new ArrayList<LotteryPhase>();
		// List<LotteryPhase> pagePhaseList = new ArrayList<LotteryPhase>();
		// 正在进行的活动
		for (LotteryPhase phase : allPhaseList) {
			// 页面显示

			if (LotteryUtil.getQuot(today, phase.getGmtStart()) <= 0
					&& LotteryUtil.getQuot(today, phase.getGmtEnd()) >= 0) {
				phaseList.add(phase);
			}
		}

		List<LotteryStatistical> statList = new ArrayList<LotteryStatistical>();

		if (logger.isInfoEnabled()) {
			logger.info("开始统计活动人数");
		}
		for (LotteryPhase phase : phaseList) {
			// 今天已经更新了
			if (phaseService.isExistStat(phase.getPhaseId(), today)) {
				message = "今天的活动人数已经更新";
				model.put("message", message);
				model.put("phaseList", phaseList);
				if (logger.isInfoEnabled()) {
					logger.info("{},活动人数已经更新", phase.getPhaseName());
				}
				return new ModelAndView("admin/insertStat", model);
			}
			// 各种等级
			for (int i = 1; i <= LotteryStatistical.LEVELNUM; i++) {
				LotteryStatistical nowstat = new LotteryStatistical();
				nowstat = phaseService.getStatValue(phase.getPhaseId(), String
						.valueOf(i), today);
				if (null == nowstat) {
					LotteryStatistical nullstat = new LotteryStatistical();
					nullstat.setPhaseId(phase.getPhaseId());
					nullstat.setPrizeLevel(String.valueOf(i));
					nullstat.setWinnerAmount(0);
					nullstat.setWinDate(today);
					statList.add(nullstat);
				} else {
					nowstat.setWinDate(today);
					statList.add(nowstat);
				}
			}
		}
		// 批量创建
		if (phaseService.batchInsertStat(statList)) {
			message = "批量创建成功";
		} else {
			message = "批量创建失败";
		}

		if (logger.isInfoEnabled()) {
			logger.info("统计活动人数结束");
		}

		model.put("message", message);
		model.put("phaseList", phaseList);
		return new ModelAndView("admin/insertStat", model);
	}

	/**
	 * 生成xydataset
	 * 
	 * @param statList
	 * @return
	 */
	private XYDataset createYearDataset(List<LotteryStatistical> statList) {

		// //统计列表
		// List<LotteryStatistical> statList =
		// phaseService.getStat(phase.getPhaseId());

		TimeSeriesCollection localTimeSeriesCollection = new TimeSeriesCollection();
		TimeSeries localTimeSeries1 = new TimeSeries(LotteryStatistical.LEVEL1);
		TimeSeries localTimeSeries2 = new TimeSeries(LotteryStatistical.LEVEL2);
		TimeSeries localTimeSeries3 = new TimeSeries(LotteryStatistical.LEVEL3);
		TimeSeries localTimeSeries4 = new TimeSeries(LotteryStatistical.LEVEL4);
		TimeSeries localTimeSeries5 = new TimeSeries(LotteryStatistical.LEVEL5);

		for (int i = 0; i < statList.size(); i++) {
			LotteryStatistical stat = statList.get(i);
			// 有异常情况
			int level = Integer.parseInt(stat.getPrizeLevel());

			// 设置数据
			switch (level) {
			case 1:
				localTimeSeries1.add(new Day(stat.getWinDate()), stat
						.getWinnerAmount());
				break;
			case 2:
				localTimeSeries2.add(new Day(stat.getWinDate()), stat
						.getWinnerAmount());
				break;
			case 3:
				localTimeSeries3.add(new Day(stat.getWinDate()), stat
						.getWinnerAmount());
				break;
			case 4:
				localTimeSeries4.add(new Day(stat.getWinDate()), stat
						.getWinnerAmount());
				break;
			case 5:
				localTimeSeries5.add(new Day(stat.getWinDate()), stat
						.getWinnerAmount());
				break;
			default:
				// ocalTimeSeries = new TimeSeries(LotteryStatistical.LEVEL6);
				break;
			}

		}

		localTimeSeriesCollection.addSeries(localTimeSeries1);
		localTimeSeriesCollection.addSeries(localTimeSeries2);
		localTimeSeriesCollection.addSeries(localTimeSeries3);
		localTimeSeriesCollection.addSeries(localTimeSeries4);
		localTimeSeriesCollection.addSeries(localTimeSeries5);

		return localTimeSeriesCollection;
	}

	/**
	 * @param phaseService
	 *            the phaseService to set
	 */
	public void setPhaseService(PhaseService phaseService) {
		this.phaseService = phaseService;
	}
}
